﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Petroleum.Tool;
using HZH_Controls.Forms;
using Petroleum.DB.Model;
using Petroleum.Model;
using HZH_Controls.Controls;
using Newtonsoft.Json;
using System.Data.SQLite;
using Sunny.UI;

namespace Petroleum.UC
{
    public partial class Step1 : UserControl
    {
        FormMain main = new FormMain();

        List<TargetModel> targetList = new List<TargetModel>();
        public Step1(FormMain main)
        {
            InitializeComponent();
            this.main = main;
            txtGL.TextChanged += TxtGL_TextChanged;
            txtKB.TextChanged += TxtKB_TextChanged;
            txtSSTVD.TextChanged += TxtSSTVD_TextChanged;
            //this.txtDesignTVD.KeyDown += new System.Windows.Forms.KeyEventHandler(ASYTool.TextBox_KeyPress);
            ToolStripManager.Renderer = new ProfessionalToolStripRendererEx();
            List<KeyValuePair<string, string>> lstCom = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("A","A"),
                new KeyValuePair<string, string>("B","B"),
            };
            cmdTarget.Source = lstCom;
            cmdTarget.SelectedIndex = 0;
        }
        private void TxtGL_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txtGL.InputText) && txtGL.InputText != ".")
                {
                    txtKB.InputText = (double.Parse(txtGL.InputText) + 7.5) + "";
                }
            }
            catch (Exception ex)
            {
                txtGL.InputText = "0";
                new UIPage().ShowErrorDialog("输入的数值不正确");
            }
        }
        private void TxtKB_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txtKB.InputText) && txtKB.InputText != ".")
                {
                    txtDesignTVD.InputText = (decimal.Parse(txtSSTVD.InputText) + decimal.Parse(txtKB.InputText)) + "";
                }
            }
            catch (Exception ex)
            {
                txtDesignTVD.InputText = "0";
                new UIPage().ShowErrorDialog("输入的数值不正确");
            }
        }
        private void TxtSSTVD_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(txtSSTVD.InputText) && txtSSTVD.InputText != "." && (txtSSTVD.InputText.Length > 1 && txtSSTVD.InputText.StartsWith("-")))
                {
                    txtDesignTVD.InputText = (0-decimal.Parse(txtSSTVD.InputText) + decimal.Parse(txtKB.InputText)) + "";
                }
            }
            catch (Exception ex)
            {
                txtSSTVD.InputText = "0";
                new UIPage().ShowErrorDialog("输入的数值不正确");
            }
        }
        private void btnTest_BtnClick(object sender, EventArgs e)
        {
            var left = ASYTool.GetControll(groupLeft);
            var right = ASYTool.GetControll(groupRight);
            Console.WriteLine("当前窗口一共" + (left.Count + right.Count) + "个输入框。");
            FrmDialog.ShowDialog(this, left + "\n" + right);
            //labTest.Text = "当前窗口一共" + (left.Count + right.Count) + "个输入框。";
        }
        bool hassave = false;
        private void btnDown_BtnClick(object sender, EventArgs e)
        {
            this.verificationComponent1.Verification();
            if (lstErrorControl.Count == 0)
            {
                Session.BasicInf = GetControl();
                LogHelper.WriteLog("Step1下一步，井口名称：" + Session.BasicInf.WellName);
                hassave = true;
                main.AddControl(new Step2FormationPressurePrediction(main));
            }
            lstErrorControl.Clear();
            this.Invalidate(true);
        }
        public BasicInf GetControl()
        {
            return new BasicInf()
            {
                WellName = txtWellName.InputText,
                TrajectoryType = txtTrajectoryType.InputText,
                WellType = txtWellType.InputText,
                LocationOfGeoStructure = txtLocation.Text,
                NameOfGeoStructure = txtNameOGS.Text,
                PurposeOfDrilling = txtPurposeOfDrilling.Text,
                TargetFormation = txtTarget.InputText,
                WellCompletionMethod = txtWellCM.InputText,
                TDCriterion = s.Text,
                Wellhead = new WellheadCoordinates()
                {
                    Longitude = txtLongitude.InputText,
                    Latitude = txtLatitude.InputText,
                    X = txtX.InputText,
                    Y = txtY.InputText
                },
                GL = txtGL.InputText,
                KB = ASYTool.IsNumeric(txtKB.InputText) ? decimal.Parse(txtKB.InputText) : 0,
                SSTVD = ASYTool.IsNumeric(txtSSTVD.InputText) ? decimal.Parse(txtSSTVD.InputText) : 0,
                DesignTVD = ASYTool.IsNumeric(txtDesignTVD.InputText) ? decimal.Parse(txtDesignTVD.InputText) : 0,
                TargetList = targetList
            };
        }
        private void ucDataGridView1_Load(object sender, EventArgs e)
        {
            List<DataGridViewColumnEntity> lstCulumns = new List<DataGridViewColumnEntity>();
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Target", HeadText = "Target", WidthType = SizeType.AutoSize, Width = 100, TextAlign = ContentAlignment.MiddleCenter });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Easting", HeadText = "Easting", WidthType = SizeType.AutoSize, Width = 100, TextAlign = ContentAlignment.MiddleCenter });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Northing", HeadText = "Northing", WidthType = SizeType.AutoSize, Width = 100, TextAlign = ContentAlignment.MiddleCenter });
            //lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "ErrorRadius", HeadText = "ErrorRadius", WidthType = SizeType.AutoSize, Width = 100, TextAlign = ContentAlignment.MiddleCenter });
            lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "TVDOfTarget", HeadText = "TVDOfTarget", WidthType = SizeType.AutoSize, Width = 200, TextAlign = ContentAlignment.MiddleCenter });
            //lstCulumns.Add(new DataGridViewColumnEntity() { DataField = "Formation", HeadText = "Formation", WidthType = SizeType.Absolute, Width = 200, TextAlign = ContentAlignment.MiddleCenter });
            this.dgv.Columns = lstCulumns;
            this.dgv.DataSource = targetList;
        }
        private void ucBtnExt1_BtnClick(object sender, EventArgs e)
        {
            if (!ASYTool.IsNumeric(txtEasting))
            {
                FrmTips.ShowTipsWarning(this.FindForm(), $"Easting的值不能是空或者其他字符，只能是数字");
                return;
            }

            if (!ASYTool.IsNumeric(txtNorthing))
            {
                FrmTips.ShowTipsWarning(this.FindForm(), $"Northing的值不能是空或者其他字符，只能是数字");
                return;
            }

            if (!ASYTool.IsNumeric(txtErrorRadius))
            {
                FrmTips.ShowTipsWarning(this.FindForm(), $"ErrorRadius的值不能是空或者其他字符，只能是数字");
                return;
            }
            if (!ASYTool.IsNumeric(txtTVDOfTarget))
            {
                FrmTips.ShowTipsWarning(this.FindForm(), $"TVDOfTarget的值不能是空或者其他字符，只能是数字");
                return;
            }
            //if (!ASYTool.IsNumeric(txtTVDOfTarget1))
            //{
            //    FrmTips.ShowTipsWarning(this.FindForm(), $"TVDOfTarget的值不能是空或者其他字符，只能是数字");
            //    return;
            //}
            TargetModel casing = new TargetModel()
            {
                Target = cmdTarget.SelectedValue,
                Easting = decimal.Parse(txtEasting.InputText),
                Northing = decimal.Parse(txtNorthing.InputText),
                ErrorRadius = decimal.Parse(txtErrorRadius.InputText),
                Formation = txtFormation.InputText,
                TVDOfTarget = txtTVDOfTarget.InputText,
            };
            //查重并删除
            var exists = targetList.Where(m => m.Target == casing.Target).FirstOrDefault();
            if (exists != null)
            {
                targetList.Remove(exists);
                FrmTips.ShowTipsInfo(this.FindForm(), $"已将Target{exists.Target}的值更新");
            }
            //targetList = new List<TargetModel>();
            targetList.Add(casing);
            this.dgv.DataSource = targetList;
        }
        List<Control> lstErrorControl = new List<Control>();
        private void verificationComponent1_Verificationed(VerificationEventArgs e)
        {
            //校验控件非空
            if (!e.IsVerifySuccess)
            {
                lstErrorControl.Add(e.VerificationControl);
            }
        }
        private void StripMenuDel_Click(object sender, EventArgs e)
        {
            if (dgv.SelectRow != null)
            {
                int row = dgv.SelectRow.RowIndex;
                targetList.RemoveAt(row);
                this.dgv.DataSource = targetList;
                return;
            }
            FrmTips.ShowTipsWarning(this.FindForm(), "请先选择要删除的行");
        }
        private void StripMenuEdit_Click(object sender, EventArgs e)
        {
            if (dgv.SelectRow != null)
            {
                int row = dgv.SelectRow.RowIndex;
                var target = targetList[row];
                FrmInputs frm = new FrmInputs($"正在编辑Targer{target.Target}",
                             new string[] { "Easting", "Northing", "TVDOfTarget" },
                             new Dictionary<string, HZH_Controls.TextInputType>() { { "Easting", HZH_Controls.TextInputType.Number }, { "Northing", HZH_Controls.TextInputType.Number }, { "TVDOfTarget", HZH_Controls.TextInputType.Number } },
                             new Dictionary<string, string>() { },
                             new Dictionary<string, KeyBoardType>() { { "Easting", KeyBoardType.UCKeyBorderNum }, { "Northing", KeyBoardType.UCKeyBorderNum }, { "TVDOfTarget", KeyBoardType.UCKeyBorderNum } },
                             new List<string>() { "Easting", "Northing", "TVDOfTarget" }, new Dictionary<string, string> {
                          { "Easting",target.Easting.ToString() },
                         { "Northing",target.Northing.ToString() },
                         { "TVDOfTarget",target.TVDOfTarget.ToString() },
                         //{ "ErrorRadius",target.ErrorRadius.ToString() }
                             });
                if (frm.ShowDialog(this) == DialogResult.OK)
                {
                    target.Easting = Convert.ToDecimal(frm.Values[0]);
                    target.Northing = Convert.ToDecimal(frm.Values[1]);
                    target.TVDOfTarget = frm.Values[2];
                    //target.ErrorRadius = Convert.ToDecimal(frm.Values[2]);
                    targetList[row] = target;
                    this.dgv.DataSource = targetList;
                    FrmTips.ShowTipsInfo(this.FindForm(), $"已将Target{target.Target}的值更新");
                }
                return;
            }
            FrmTips.ShowTipsWarning(this.FindForm(), "请先选择要编辑的行");
        }
        private void btnword_BtnClick(object sender, EventArgs e)
        {
            var BasicInf = main.projects.Where(n => n.TableName == TableNames.BasicInf.ToString()).FirstOrDefault();
            if (BasicInf != null)
            {
                Session.BasicInf = JsonConvert.DeserializeObject<BasicInf>(BasicInf.TableData);
                if (Session.BasicInf.TargetList != null)
                {
                    targetList = Session.BasicInf.TargetList;
                    if (targetList.Count > 0)
                    {
                        txtTVDOfTarget.InputText = targetList[0].TVDOfTarget;
                        //txtTVDOfTarget1.InputText = targetList[0].TVDOfTargetTo;
                        txtErrorRadius.InputText = targetList[0].ErrorRadius + "";
                    }
                    dgv.DataSource = targetList;
                }
                txtWellName.InputText = Session.BasicInf.WellName;
                txtTrajectoryType.InputText = Session.BasicInf.TrajectoryType;
                txtWellType.InputText = Session.BasicInf.WellType;
                txtLocation.Text = Session.BasicInf.LocationOfGeoStructure;
                txtNameOGS.Text = Session.BasicInf.NameOfGeoStructure;
                txtPurposeOfDrilling.Text = Session.BasicInf.PurposeOfDrilling;
                txtTarget.InputText = Session.BasicInf.TargetFormation;
                txtWellCM.InputText = Session.BasicInf.WellCompletionMethod;
                s.Text = Session.BasicInf.TDCriterion;
                if (Session.BasicInf.Wellhead != null)
                {
                    txtLongitude.InputText = Session.BasicInf.Wellhead.Longitude;
                    txtLatitude.InputText = Session.BasicInf.Wellhead.Latitude;
                    txtX.InputText = Session.BasicInf.Wellhead.X;
                    txtY.InputText = Session.BasicInf.Wellhead.Y;
                }
                txtGL.InputText = Session.BasicInf.GL;
                txtKB.InputText = Session.BasicInf.KB + "";
                txtSSTVD.InputText = Session.BasicInf.SSTVD + "";
                txtDesignTVD.InputText = Session.BasicInf.DesignTVD + "";
            }
        }
        private void btnsave_BtnClick(object sender, EventArgs e)
        {
            if (!hassave)
                Session.BasicInf = GetControl();
            SQLiteDataReader reader = main.sqliteHelper.ReadFullTable("SessionData");
            //利用魔法将(SQLite)DataReader转换为List
            var projects = EntityTranslate.Translate<SessionData>(reader);
            var BasicInfo = projects.Where(n => n.TableName == TableNames.BasicInf.ToString()).FirstOrDefault();
            if (BasicInfo != null)
                SQLiteHelper.SaveData(main.sqliteHelper, TableNames.BasicInf.ToString(), JsonConvert.SerializeObject(Session.BasicInf));
            else
                SQLiteHelper.SaveData(main.sqliteHelper, TableNames.BasicInf.ToString(), JsonConvert.SerializeObject(Session.BasicInf), 1);
            FrmTips.ShowTipsSuccess(new FormMain(), "保存成功");
        }
    }
}
